package com.beemans.common.utils

import android.Manifest.permission
import android.location.*
import androidx.annotation.RequiresPermission
import com.blankj.utilcode.util.Utils
import com.tiamosu.fly.utils.locationManager
import java.util.*

/**
 * @author tiamosu
 * @date 2021/8/11.
 */
object LocationUtils {

    /**
     * @return 获取位置信息
     *
     * @param criteriaOption
     * @param defaultProvider
     * @param locale
     */
    @RequiresPermission(anyOf = [permission.ACCESS_COARSE_LOCATION, permission.ACCESS_FINE_LOCATION])
    fun getLocation(
        criteriaOption: Criteria.() -> Unit = {},
        defaultProvider: String = LocationManager.NETWORK_PROVIDER,
        locale: Locale = Locale.CHINESE,
        onFailed: (msg: String) -> Unit = {},
        onSuccess: (location: Location, address: Address) -> Unit = { _, _ -> }
    ) {
        fun updateLocation(location: Location) {
            kotlin.runCatching {
                val geocoder = Geocoder(Utils.getApp(), locale)
                val longitude = location.longitude
                val latitude = location.latitude
                val addressList = geocoder.getFromLocation(latitude, longitude, 1)
                if (addressList.isNullOrEmpty()) {
                    onFailed.invoke("获取位置信息失败")
                }
                val address = addressList[0]
                onSuccess.invoke(location, address)
            }.onFailure {
                onFailed.invoke(it.message ?: "获取位置信息失败")
            }
        }

        val criteria = Criteria().apply {
            //设置精度要求（Criteria.ACCURACY_COARSE：粗略；Criteria.ACCURACY_FINE：精细）
            accuracy = Criteria.ACCURACY_COARSE
            //是否要求能提供高度的信息
            isAltitudeRequired = false
            //是否要求能提供方向信息
            isBearingRequired = false
            //是否允许产生资费
            isCostAllowed = true
            //设置耗电量
            powerRequirement = Criteria.POWER_LOW
            //是否要求能提供速度信息
            isSpeedRequired = false

        }.apply(criteriaOption)

        val provider =
            locationManager?.getBestProvider(criteria, true) ?: defaultProvider
        val location = locationManager?.getLastKnownLocation(provider)
        location?.let { updateLocation(it) }
    }
}